<template>
  <div class="base-view" v-loading="loading">
    <AppItem class="app-item-view" v-for="item in apps" :key="item.id" :itemModel="item" :isAdmin="isAdmin" :enable="item.enable" @deleteClick="doDelete(item)"
             @editClick="doEdit(item)" @getDetail="getDetail(item)" @qrcodeClick="handleQRCode(item)"/>

    <div class="app-add-base-view" v-if="isAdmin" @click="addApp">
      <img class="app-add-logo" src="@/assets/tianjia.png"/>
      <h1 class="app-add-label">新增应用</h1>
    </div>

    <el-dialog :title="dialogType == 0 ? '新增应用' : '编辑应用'" :visible.sync="dialogFormAppEditVisible">
      <el-form :model="appInfo" label-position="top">
        <el-form-item label="应用名" require="true">
          <el-input v-model="appInfo.name" autocomplete="off" placeholder="请输入应用名"></el-input>
        </el-form-item>
        <el-form-item label="LOGO" require="true">
          <div class="appEdit-logo-view">
            <img class="appEdit-logo-img" :src="appInfo.logoUrl"/>
            <el-upload
              class="upload-demo"
              drag
              action="/"
              :data="uploadData"
              :http-request="httpRequest"
              :on-success="successFile"
              :show-file-list="false"
              accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.GIF">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将Logo拖到此处，或<em>点击上传</em></div>
              <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="dialog-btn-ok" @click="changeAppEditClick">确 定</el-button>
        <el-button class="dialog-btn-cancel" @click="dialogFormAppEditVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="推广设置" :visible.sync="showQRCode" @opened="qrOpened" width="30%" top="3vh" :close-on-click-modal="false" :close-on-press-escape="false">
        <div class="dialogBase">
          <div class="qrcodeBase" ref="codeImg">
            <div class="qrcode" id="qrCodeUrl" ref="qrCodeUrl"></div>
            <img class="qrcodeImg" :src="appInfo.logoUrl"/>
            <div class="qrcodeTitle">{{appInfo.promoteVersion}}</div>
          </div>
          <el-form label-width="120px" :model="appInfo" label-position="top" size="mini" style="width: 90%;">
            <el-form-item label="环境/版本信息">
              <el-input v-model="appInfo.promoteVersion" placeholder="最长50字" maxlength="50" :disabled="!appInfo.enable"></el-input>
            </el-form-item>
            <el-form-item label="应用名">
              <el-input v-model="appInfo.promoteName" placeholder="最长50字" maxlength="50" :disabled="!appInfo.enable"></el-input>
            </el-form-item>
            <el-form-item label="推广语">
              <el-input v-model="appInfo.promoteDesc" placeholder="最长50字" maxlength="50" :disabled="!appInfo.enable"></el-input>
            </el-form-item>
            <el-form-item label="简介">
              <el-input type="textarea" v-model="appInfo.promoteIntroduction" placeholder="最长200字" maxlength="200" rows="6" :disabled="!appInfo.enable"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button class="dialog-btn-download" @click="downloadQRCode">下载二维码</el-button>
            <el-button class="dialog-btn-ok" @click="changeAppEditClick" v-if="appInfo.enable">保存文案</el-button>
          </div>
        </div>
    </el-dialog>
  </div>
</template>

<script>
  import AppItem from './component/item'
  import store from '@/store'
  import {saveKeys} from '@/utils/enums'
  import {Message} from 'element-ui'
  import QRCode from 'qrcodejs2'
  import {apkUpload} from '@/api/appEdit'
  import defaultLogo from '@/assets/logo.png'
  import html2canvas from 'html2canvas';

  import {
    getAllApps,
    getAndroidVersions,
    getIOSVersions,
    appUpdate,
    appInsert,
    appDelete,
    selectMenuPermissionsByAppIDAndUserId
  } from '@/api/main'

  export default {
    name: 'MainPage',
    components: {AppItem},
    data() {
      return {
        loading: false,
        // 模型{ appId, appKey, name, updateDate}
        apps: [],
        // 是否显示应用编辑框
        dialogFormAppEditVisible: false,
        // 编辑框类型：0-新增，1-编辑
        dialogType: 0,
        appInfo: {},
        isEdit: false,
        isAdmin: false,
        // logo上传data
        uploadData: {},
        // 是否展示二维码编辑窗
        showQRCode: false
      }
    },
    created() {
      this.isAdmin = this.$store.getters.accessUser.isAdmin == 1;
      this.reload(function () {
        var that = this
        store.dispatch('getAndroidVersions').then(() => {
          // 将安卓所有版本号存入sessionStorage
          sessionStorage.setItem(saveKeys().ANDROID_VERSIONS,JSON.stringify(store.getters.androidVersions));
        })
        store.dispatch('getIOSVersions').then(() => {
          // 将iOS所有版本号存入sessionStorage
          sessionStorage.setItem(saveKeys().IOS_VERSIONS,JSON.stringify(store.getters.iOSVersions));
        })

        store.dispatch('getNotices').then(() => {
          // 将所有通知类型存入sessionStorage
          sessionStorage.setItem(saveKeys().ALL_NOTICE_TYPES,JSON.stringify(store.getters.notices));
        })
      });
    },
    methods: {
      reload(success) {
        new Promise((resolve, reject) => {
          getAllApps().then(response => {
            const data = response.data
            this.apps = data.repData
            resolve(response)
            success()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 点击删除
      doDelete(item) {
        new Promise((resolve, reject) => {
          appDelete(item).then(response => {
            if (response != undefined) {
              this.reload();
            }
            resolve(response)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 点击编辑
      doEdit(item) {
        this.isEdit = true;
        // this.appInfo.name = item.name
        // this.appInfo.appId = item.appId
        this.dialogFormAppEditVisible = true;
        this.dialogType = 1;
        this.uploadData.appId = item.appId

        this.appInfo = {...item}
        if(this.appInfo.logoUrl == null) {
          this.appInfo.logoUrl = defaultLogo
        }
      },
      addApp() {//添加APP
        this.isEdit = false;
        this.appInfo = {}
        this.appInfo.logoUrl = defaultLogo
        this.dialogFormAppEditVisible = true;
        this.dialogType = 0;
      },
      changeAppEditClick() {
        if(this.appInfo.name == '') {
          Message({
            message: '请输入应用名',
            type: 'warning',
            duration: 5 * 1000
          });
          return;
        }
        if (this.isEdit) {
          new Promise((resolve, reject) => {
            appUpdate(this.appInfo).then(response => {
              if (response != undefined) {
                this.reload();
              }
              Message({
                message: '保存成功',
                type: 'success',
                duration: 1000
              });
              resolve(response)
              this.showQRCode = false
              this.dialogFormAppEditVisible = false;
            }).catch(error => {
              reject(error)
            })
          })
        } else {
          new Promise((resolve, reject) => {
            appInsert(this.appInfo).then(response => {
              if (response != undefined) {
                this.reload();
              }
              Message({
                message: '保存成功',
                type: 'success',
                duration: 1000
              });
              resolve(response)
              this.showQRCode = false
              this.dialogFormAppEditVisible = false;
            }).catch(error => {
              reject(error)
            })
          })
        }

      },
      // 进入app详情
      getDetail(item) {
        new Promise((resolve, reject) => {
          selectMenuPermissionsByAppIDAndUserId({appId: item.appId}).then(response => {
            if (response != undefined) {
              // perms
              const data = response.data.repData;
              if (data.length > 0){
                var paramsList = [];
                for (let index in data) {
                  paramsList.push(data[index].perms)
                }

                // 进入app详情储存当前appId、appKey、appName到sessionStorage
                let info = {
                  appId: item.appId,
                  appKey: item.appKey,
                  appName: item.name
                };
                sessionStorage.setItem(saveKeys().APP_INFO,JSON.stringify(info));

                this.$store.dispatch('UpdateAppInfo', {appId: item.appId, appKey: item.appKey, perms: paramsList, appName: item.name})
                if (paramsList.length > 0 ) {
                  // 获取第一个权限，作为跳转的默认页面
                  if(paramsList[0] == 'system:user:notice') {
                    this.$router.push({path: '/app/notification'});
                  }else if(paramsList[0] == 'system:user:version') {
                    this.$router.push({path: '/app/version'});
                  }else if(paramsList[0] == 'system:user:members') {
                    this.$router.push({path: '/app/member'});
                  }else if(paramsList[0] == 'system:user:push') {
                    this.$router.push({path: '/app/pushconfig'});
                  }
                }else {// 没有此App的权限，弹出提示
                  Message({
                    message: '没有编辑此App的权限',
                    type: 'warning',
                    duration: 5 * 1000
                  });
                }
              }
            }
            resolve(response)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 编辑推广二维码
      handleQRCode(item) {
        this.isEdit = true
        this.uploadData.appId = item.appId
        this.appInfo = {...item}
        if(this.appInfo.logoUrl == null) {
          this.appInfo.logoUrl = defaultLogo
        }
        console.log("url--info", window.location.origin);
        // let { href } = this.$router.resolve({ path: '/promote', query: {appid: item.appId}})
        // window.open(href, '_blank')
        this.showQRCode = true
      },
      qrOpened(e) {
        // document.getElementById("qrCodeUrl").innerHTML = "";
        this.$refs.qrCodeUrl.innerHTML = '' 
        var qrcode = new QRCode(this.$refs.qrCodeUrl, {
            text: window.location.origin + '/#/promote?appkey=' + this.appInfo.appKey, // 需要转换为二维码的内容
            width: 150,
            height: 150,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.Q
        })
      },
      /**
       *文件上传成功时的钩子
       * */
      successFile() {
        this.$message({
          message: '上传成功',
          type: 'success',
          duration: 1000
        })
      },
      httpRequest(data) {
        var formData = new FormData();
        var appId = data.data.appId;
        if (appId == null || appId == undefined) {
            appId = ''
        }
        // 图片文件
        formData.append('fileUpload', data.file);
        // 应用的AppId
        formData.append('appId', appId);
        // 文件上传类型： 0-apk文件，1-图片文件
        formData.append('type', 1);
        this.loading = true;
        apkUpload(formData).then(response => {
          if (response != undefined) {
            const data = response.data.repData;
            this.appInfo.logoUrl = data.urlPath
            this.successFile();
            this.loading = false;
          }
        }, error => {
          this.loading = false;
        })
      },
      // 下载二维码
      downloadQRCode() {
        html2canvas(this.$refs.codeImg).then(canvas => {
          let link = document.createElement("a");
          link.href = canvas.toDataURL();//下载链接
          link.setAttribute("download", this.appInfo.name + ".png");
          link.style.display = "none";//a标签隐藏
          document.body.appendChild(link);
          link.click();
        });
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  @import "../../styles/common.css";

  .base-view {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    padding: 20px;
    align-items: center;
    justify-content: flex-start;
  }

  .app-item-view {
    margin: 10px;
  }

  .app-add-base-view {
    cursor:pointer;
    margin: 10px;
    width: 23%;
    height: 170px;
    background-color:#fff;
    padding: 15px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    -moz-box-shadow: 0px 0px 7px rgba(54, 141, 255, 0.2);
    -webkit-box-shadow: 0px 0px 7px rgba(54, 141, 255, 0.2);
    box-shadow: 0px 0px 7px rgba(54, 141, 255, 0.2);

    border-width: 1px;
    border-color:green;
    border-style: dashed;
  }

  .app-add-logo {
    object-fit: contain;
    width: 20%;
  }

  .app-add-label {
    font-size: 16px;
  }

  .dialogBase {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .qrcodeTitle {
    /* width: 100%; */
    min-height: 20px;
    margin-top: 10px;
    margin-bottom: 10px;
    text-align: center;
  }

  .qrcodeBase {
    /* width: 100%; */
    width: 180px;
    padding-top: 10px;
    /* height: 170px; */
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .qrcode {
    width: 150px;
    height: 150px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  .qrcodeImg {
    width: 50px;
    height: 50px;
    position: absolute;
    top: 60px;
    left: calc(50% - 25px);
    border-radius: 25px;
    padding: 5px;
    background-color: #fff;
  }

  .appEdit-logo-view {
    width: 100%;
    display: flex;
    flex-direction: row;
    /* align-items: center; */
    /* justify-content: center; */
    /* background-color: coral; */
  }

  .appEdit-logo-img {
    width: 180px;
    height: 180px;
    border-style: solid;
    border-width: 1px;
    border-radius: 20px;
    border-color: #ebebeb;
    margin-right: 10px;
    object-fit: contain;
    /* background-color: cornflowerblue; */
  }
</style>
